package com.xcx.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xcx.commonuntils.JwtUtils;
import com.xcx.commonuntils.MD5;
import com.xcx.commonuntils.returnuntls.ErrorEnum;
import com.xcx.commonuntils.returnuntls.ReturnMessage;
import com.xcx.commonuntils.returnuntls.ReturnMessageUtils;
import com.xcx.eduservice.entity.logentity.UcenterMember;
import com.xcx.eduservice.entity.aclentity.Permission;
import com.xcx.eduservice.entity.aclentity.User;
import com.xcx.eduservice.entity.aclentity.UserRole;
import com.xcx.eduservice.mapper.UcenterMemberMapper;
import com.xcx.eduservice.mapper.UserMapper;
import com.xcx.eduservice.request.aclrequest.userrequest.UserGetProcessionRequest;
import com.xcx.eduservice.request.logrequest.LogWxRequest;
import com.xcx.eduservice.request.logrequest.RegisterRequest;
import com.xcx.eduservice.request.logrequest.UcenterRequest;
import com.xcx.eduservice.response.AssignResponse;
import com.xcx.eduservice.response.loginindexresponse.LoginUserInfoResponse;
import com.xcx.eduservice.service.PermissionService;
import com.xcx.eduservice.service.UcenterMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcx.eduservice.service.UserRoleService;
import com.xcx.eduservice.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;


/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-10-10
 */
@Slf4j
@Service
@Primary
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    final private RedisTemplate<String, String> redisTemplate;
    final private UserService userService;
    final private UserRoleService userRoleService;
    final private UserMapper userMapper;
    final private PermissionService permissionService;

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ReturnMessage<LoginUserInfoResponse> login(UcenterRequest member) {
        //获取登录手机号和密码
        String mobile = member.getMobile();
        String password = member.getPassword();

        //手机号和密码非空判断
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            ReturnMessageUtils.errorWithEum(ErrorEnum.E_UCENTER_PHNOE_PASSWORD);
        }

        //判断手机号是否正确
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        UcenterMember mobileMember = baseMapper.selectOne(wrapper);
        //判断查询对象是否为空
        if (mobileMember == null) {//没有这个手机号
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_UCENTER_PHNOE);
        }


        //判断密码
        //因为存储到数据库密码肯定加密的
        //把输入的密码进行加密，再和数据库密码进行比较
        //加密方式 MD5
        if (!MD5.encrypt(password).equals(mobileMember.getPassword())) {
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_UCENTER_PHNOE_LOGIN);
        }

        //判断用户是否禁用
        if (mobileMember.getIsDisabled()) {
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_UCENTER_PHNOE_LOGIN);
        }
        //登录成功
        //生成token字符串，使用jwt工具类
        String jwtToken = JwtUtils.getJwtToken(mobileMember.getId(), mobileMember.getNickname());

        mobileMember.setJwtToken(jwtToken);
        //同时把登陆人员新增到用户表，默认普通会员
        //判断登陆人员是否为用户


        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("mobile", mobile);
        User userinfo = userService.getOne(userQueryWrapper);
        if (userinfo == null){
            User user = new User();
            user.setMobile(mobileMember.getMobile());
            user.setPassword(mobileMember.getPassword());
            user.setToken(jwtToken);
            userMapper.insert(user);
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId("1196300996034977794");
            userRoleService.saveOrUpdate(userRole);
            return getLoginUserInfoResponseReturnMessage(user);

        }
        return getLoginUserInfoResponseReturnMessage(userinfo);

    }


    private ReturnMessage<LoginUserInfoResponse> getLoginUserInfoResponseReturnMessage(User userinfo) {
        LoginUserInfoResponse loginUserInfoResponse = new LoginUserInfoResponse();
        UserGetProcessionRequest userGetProcessionRequest = new UserGetProcessionRequest();
        userGetProcessionRequest.setId((userinfo.getId()));
        ReturnMessage<List<Permission>> promissByUserId = permissionService.getPromissByUserId(userGetProcessionRequest);
        if (promissByUserId != null){
            List<Permission> data = promissByUserId.getData();
            for (Permission p:data
                 ) {
                loginUserInfoResponse.getPermissionList().add(p);
            }
        }
        ReturnMessage<AssignResponse> assignResponseReturnMessage = userService.toAssign(userGetProcessionRequest);
        BeanUtils.copyProperties(assignResponseReturnMessage.getData(), loginUserInfoResponse.getAssignResponse());
        return ReturnMessageUtils.success(loginUserInfoResponse);
    }

    @Override
    public ReturnMessage<Object> register(RegisterRequest registerVo) {
        //获取注册的数据
        String code = registerVo.getCode(); //验证码
        String mobile = registerVo.getMobile(); //手机号
        String nickname = registerVo.getNickname(); //昵称
        String password = registerVo.getPassword(); //密码

        //非空判断
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(code) || StringUtils.isEmpty(nickname)) {
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_UCENTER_PHNOE_PASSWORD);
        }
        //判断验证码
        //获取redis验证码
        String redisCode = redisTemplate.opsForValue().get(mobile);
        if(!code.equals(redisCode)) {
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_UCENTER_CODE_FAIL);
        }

        //判断手机号是否重复，表里面存在相同手机号不进行添加
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile",mobile);
        Integer count = baseMapper.selectCount(wrapper);
        if(count > 0) {
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_UCENTER_PHNOE_REPERT);
        }

        //数据添加数据库中
        UcenterMember member = new UcenterMember();
        member.setMobile(mobile);
        member.setNickname(nickname);
        member.setPassword(MD5.encrypt(password));//密码需要加密的
        member.setIsDisabled(false);//用户不禁用
        //baseMapper.insert(member);
        log.info("注册信息:",member);
        this.saveOrUpdate(member);

        return ReturnMessageUtils.success();
    }


    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public ReturnMessage<LoginUserInfoResponse> loginWx(LogWxRequest member) {
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",member.getOpenid());
        UcenterMember ucenterMember = baseMapper.selectOne(wrapper);
        if (ucenterMember == null){
            UcenterMember ucenterMember1 = new UcenterMember();
            BeanUtils.copyProperties(member, ucenterMember1);
            ucenterMember1.setAvatar(member.getSalt());
            baseMapper.insert(ucenterMember1);
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",member.getOpenid());
        User wxUser = userMapper.selectOne(userQueryWrapper);
        if (wxUser == null){
            User user = new User();
            BeanUtils.copyProperties(member, user);
            user.setUsername(member.getOpenid());
            userMapper.insert(user);
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId("1196300996034977794");
            userRoleService.saveOrUpdate(userRole);
            return getLoginUserInfoResponseReturnMessage(user);
        }
        //返回数据信息
        return getLoginUserInfoResponseReturnMessage(wxUser);
    }
}
